# coding=utf-8

from subprocess import Popen
import subprocess
import os
import traceback

from src import logger
from src.public.public import ParseXml
from src import Config
from runtest import update_aborted_data


def stop():
	try:
		logger.info('正在终止自动化构建')
		xml = ParseXml(filepath=os.path.join(Config.project_dir, "automation.data"))
		running_pid = xml.get_value_from_xpath(xpath="./BuildData/RunningPID", attribute="pid")
		logger.info('获取到构建进程pid {}'.format(running_pid))
		cmd = 'taskkill /PID {} /F /T'.format(running_pid)
		p = Popen(cmd,
				  shell=True,
				  stdin=subprocess.PIPE,
				  stdout=subprocess.PIPE,
				  stderr=subprocess.STDOUT,
				  universal_newlines=True)
		returncode = p.wait(30)
		stdout, stderr = p.communicate()
		if returncode != 0 or stderr:
			logger.error('终止构建失败，失败原因：\n' + stdout or stderr)
		else:
			update_aborted_data()
			logger.info('自动化构建已停止，详细信息：\n' + stdout)
	except Exception:
		logger.error("终止构建失败。报错信息:\n" + traceback.format_exc())


if __name__ == "__main__":
	stop()
